import AMapLoader from "@amap/amap-jsapi-loader";

declare global {
  interface Window {
    _AMapSecurityConfig: {
      securityJsCode: string;
    };
  }
}

export default function () {
  // 高德地图API KEY
  const apiKey = "272fb8f8184785b458a7fc013c9aee43";
  // 城市名称
  let cityName = ref("");
  // 天气信息
  let weaterInfo = reactive({
    weather: "",
    temperature: "",
    windDirection: "",
    windPower: "",
  });

  async function initMap() {
    // 安全密钥
    window._AMapSecurityConfig = {
      securityJsCode: "c1b9edfed89e7fbaa5486856149b9b6f",
    };

    const AMap = await AMapLoader.load({
      key: apiKey,
      version: "2.0",
      plugins: ["AMap.CitySearch", "AMap.Weather"],
    });

    // 实例化城市查询类
    const citySearch = new AMap.CitySearch();
    // 实例化天气查询类
    const weather = new AMap.Weather();

    // 自动获取用户IP，返回当前城市
    citySearch.getLocalCity(function (status: string, result: any) {
      if (status === "complete" && result.info === "OK") {
        onComplete(result);
      } else {
        onError(result);
      }
    });

    function onComplete(data: any) {
      cityName.value = data.city;

      // 查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
      weather.getLive(cityName.value, function (err: any, data: any) {
        if (!err) {
          weaterInfo.weather = data.weather;
          weaterInfo.temperature = data.temperature;
          weaterInfo.windDirection = data.windDirection;
          weaterInfo.windPower = data.windPower;
        }
      });
    }

    function onError(data: any) {
      ElMessage.error("获取城市信息失败！");
      console.error(data);
    }
  }

  return { cityName, weaterInfo, initMap };
}
